package com.pirestupppai.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.bean.TupaiError;
import com.pirestupppai.bean.UploadFile;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.utils.FileUtil;
import com.pirestupppai.utils.ImageIOManager;
import com.pirestupppai.utils.ImageLoadUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.ProgressingDialog;
import com.pirestupppai.widgets.view.AvatarView;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.pirestupppai.rxbus.RxBus.RXBUS_REFRESH_PROFILE;
import static com.pirestupppai.utils.ImageIOManager.AVATAR_IMAGE_PATH;

/**
 * 编辑个人资料
 *
 * @author: xiaoluo
 * @date: 2017-04-28 10:31
 */
public class EditInfoActivity extends BaseActivity {

    private static final int REQUEST_CODE_SELECT = 100;
    private static final int REQUEST_CODE_ZOOM = 110;

    @BindView(R.id.edit_avatar_layout)
    RelativeLayout avatarLayout;
    @BindView(R.id.edit_avtar)
    AvatarView avatar;
    @BindView(R.id.edit_camera)
    ImageView cameraIv;
    @BindView(R.id.edit_nickname)
    EditText nicknameEt;
    @BindView(R.id.edit_desc)
    EditText descEt;
    @BindView(R.id.edit_save_tv)
    TextView saveTv;

    private String mAvatarUrl;
    private String mNickname;
    private String mDesc;

    private Uri mUri;
    private String mTempAvatarUrl = "temp.jpg";
    private String mNewAvatarPath = "";
    private String mNewAvatarName = "";

    private UploadManager mUploadManager;  // 上传
    private ProgressingDialog mDialog;


    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initViews() {
        mAvatarUrl = LoginUser.getInstance().getAvatar();
        mNickname = LoginUser.getInstance().getNickname();
        mDesc = LoginUser.getInstance().getSignature();

        nicknameEt.setText(mNickname);
        descEt.setText(mDesc);
        if (!TextUtils.isEmpty(mNickname)) {
            nicknameEt.setSelection(mNickname.length());
        }
        ImageLoadUtil.getInstance().loadAvatar(mAvatarUrl, avatar);

        ImageIOManager.getInstance();
        mUri = Uri.fromFile(new File(AVATAR_IMAGE_PATH, mTempAvatarUrl));

        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                .recorder(null)  // recorder分片上传时，已上传片记录器。默认null
                .recorder(null, null)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.httpsAutoZone) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

        mUploadManager = new UploadManager(config);
        mDialog = new ProgressingDialog(mContext);
    }

    @Override
    protected void initListeners() {
        avatar.setOnClickListener(this);
        cameraIv.setOnClickListener(this);
        saveTv.setOnClickListener(this);
    }

    @Override
    protected void initLogic() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_avtar:
            case R.id.edit_camera:
                Intent intent = new Intent(mContext, SelectPictureActivity.class);
                intent.putExtra(Constant.IntentKey.RELEASE_TYPE, Constant.SELECT_TYPE_REVISE);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                break;
            case R.id.edit_save_tv:
                save();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }

        switch (requestCode) {
            case REQUEST_CODE_SELECT:
                if (TextUtils.isEmpty(data.getStringExtra(Constant.IntentKey.SELECT_LIST))) {
                    return;
                }
                startPhotoZoom(Uri.fromFile(new File(data.getStringExtra(Constant.IntentKey.SELECT_LIST))));
                break;
            case REQUEST_CODE_ZOOM:
                try {
                    String name = "avatar_" + System.currentTimeMillis();
                    Bitmap bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(mUri));
                    String path = ImageIOManager.getInstance().saveAvatar(name, bitmap);
                    ImageLoadUtil.getInstance().loadAvatar(path, avatar, ImageLoadUtil.LoadOption.LOAD_LOCAL_AVATAR);
                    mNewAvatarPath = path;
                    mNewAvatarName = name;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 保存
     */
    private void save() {
        if (nicknameEt.getText().toString().trim().length() > 15 || nicknameEt.getText().toString().trim().length() < 1) {
            Utils.showToast("昵称字数在1-15之间");
            return;
        }
        mNickname = nicknameEt.getText().toString().trim();

//        if (descEt.getText().toString().trim().length() > 32 || descEt.getText().toString().trim().length() < 1) {
//            Utils.showToast("简介字数在1-32之间");
//            return;
//        }
        mDesc = descEt.getText().toString().trim();


        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }
        saveTv.setClickable(false);

        // 上传新头像或直接修改信息
        if (!TextUtils.isEmpty(mNewAvatarPath)) {
            getUploadToken(mNewAvatarName, mNewAvatarPath);
        } else {
            reviseProfile(-1);
        }
    }

    /**
     * 获取上传token
     */
    private void getUploadToken(String name, final String path) {
        NetworkRequest.getInstance().getUploadToken(name, this,
                new TupaiSubscriber<UploadFile>(mContext) {
                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        if (TextUtils.isEmpty(uploadFile.getToken())) {
                            return;
                        }
                        uploadToQiniu(uploadFile, path);
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    /**
     * 上传到七牛
     */
    private void uploadToQiniu(final UploadFile uploadFile, String path) {
        mUploadManager.put(path, uploadFile.getKey(), uploadFile.getToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if (info.isOK()) {
                            checkUpload(uploadFile.getUpload_id());
                        } else {
                            uploadError("info is no OK");
                        }
                    }
                }, null);
    }

    /**
     * 上传检查
     */
    private void checkUpload(final int upload_id) {
        NetworkRequest.getInstance().checkUpload(upload_id, this,
                new TupaiSubscriber<UploadFile>(mContext) {

                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        reviseProfile(upload_id);
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    /**
     * 上传失败
     */
    private void uploadError(String error) {
        saveTv.setClickable(true);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }


    /**
     * 修改请求
     */
    private void reviseProfile(int uploadId) {
        Map<String, String> info = new HashMap<>();
        if (uploadId != -1) {
            info.put("avatar_upload_id", String.valueOf(uploadId));
        }
        if (!mNickname.equals(LoginUser.getInstance().getNickname())) {
            info.put("nickname", mNickname);
        }
        info.put("signature", mDesc);
        NetworkRequest.getInstance().reviseProfileInfo(info, this,
                new TupaiSubscriber<List<TupaiError>>(mContext) {
                    @Override
                    protected void requestSuccess(List<TupaiError> data) {
                        if (data == null) {
                            RxBus.getInstance().post(RXBUS_REFRESH_PROFILE, "request");
                            Utils.showToast("修改成功");
                            finish();
                        } else {
                            String error = "";
                            for (int i = 0; i < data.size(); i++) {
                                error += data.get(i).getField() + " : " + data.get(i).getInfo();
                                if (i != data.size() - 1) {
                                    error += "\n";
                                }
                            }
                            Utils.showToast(error);
                            uploadError(error);
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    
    /**
     * 裁剪图片
     */
    private void startPhotoZoom(Uri uri) {
        if (uri != null) {
            Intent intent = new Intent("com.android.camera.action.CROP");
//            intent.setDataAndType(uri, "image/*");
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                String url = FileUtil.getPath(mContext, uri);
                intent.setDataAndType(Uri.fromFile(new File(url)), "image/jpeg");
            } else {
                intent.setDataAndType(uri, "image/*");
            }
            // 设置裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 500);
            intent.putExtra("outputY", 500);
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("scale", true);
            intent.putExtra("scaleUpIfNeeded", true);

            startActivityForResult(intent, REQUEST_CODE_ZOOM);
        }
    }
}
